SessionStorage , Server-Side Sessions


1. sessionStorage

sessionStorage is a type of web storage that allows you to store data for the duration of the page session. This data is accessible only within the same tab or window and is cleared when the tab or window is closed.

Key Features:

Common Methods:

Example:

// Store data
sessionStorage.setItem('username', 'JohnDoe');

// Retrieve data
let username = sessionStorage.getItem('username');
console.log(username); // Outputs: JohnDoe

// Remove data
sessionStorage.removeItem('username');

// Clear all data
sessionStorage.clear();

2. Server-Side Sessions

Server-side sessions are managed on the server and typically involve setting an HTTP cookie in the browser. This cookie is sent with every request to the server, allowing the server to maintain state across multiple requests.

Key Features:

Example with Express.js:

const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.send(`Number of views: ${req.session.views}`);
  } else {
    req.session.views = 1;
    res.send('Welcome to the session demo. Refresh!');
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Differences Between sessionStorage and localStorage

Use Cases: